package com.xspace.android.xafcommon.db.dbsub;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xspace.android.xafcommon.been.MediaBean;
import com.xspace.android.xafcommon.db.BaseSql;
import com.xspace.android.xafcommon.util.LogUtil;

import java.util.ArrayList;
import java.util.List;


public class FileUploadDBBiz extends BaseSql {

    public static final String tableName = "WorkLogFile ";
    public static final String tableNameTemp = "WorkLogFile_temp ";

    public static final String InsertTime = "insertTime";
    public static final String FileType = "file_type";
    public static final String FileUrl = "file_url";
    public static final String FileName = "file_name";
    public static final String FileState = "file_state";

    //数据库40更新及新增字段
    //本地路径 更新remark1
    public static final String FilePath = "file_path";
    //文件后缀名 更新remark2
    public static final String FileSuffix = "file_suffix";
    public static final String PicShootTime = "pic_shoot_time";
    public static final String Remark1 = "remark1";
    public static final String Remark2 = "remark2";

    private MyDBHelper helpDb;
    private SQLiteDatabase sqldb;

    public static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + tableName
            + " (_ID INTEGER PRIMARY KEY AUTOINCREMENT,"
            + InsertTime + " text,"
            + FileType + " text,"
            + FileUrl + " text,"
            + FileName + " text,"
            + FileState + " text,"
            + FilePath + " text,"
            + FileSuffix + " text,"
            + PicShootTime + " text,"
            + Remark1 + " text,"
            + Remark2 + " text)";

    public static final String RENAME_TO_TEMP_TABLE = "ALTER TABLE " + tableName + " RENAME TO " + tableNameTemp;
    public static final String DROP_TEMP_TABLE = "DROP TABLE IF EXISTS " + tableNameTemp;
    public static char str = '"';
    public static final String COPY_TEMP_TO_NEW_TABLE = "INSERT INTO " + tableName + " SELECT " +
            "_ID" + "," +
            "insertTime  " + "," +
            FileType + "," +
            FileUrl + "," +
            FileName + "," +
            FileState + "," +
            Remark1 + "," +
            Remark2 + "," +
            str + str + "," +
            str + str + "," +
            str + str +
            "  FROM " + tableNameTemp;

    public FileUploadDBBiz(MyDBHelper db) {
        super(db);
        helpDb = db;
    }

    protected void checkDb() {
        if (sqldb == null || !sqldb.isOpen()) {
            sqldb = helpDb.getWritableDatabase();
        }
    }

    public void closeDbAndCursor(Cursor cursor) {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
        /*
         * if (db != null) { db.close(); db = null; }
         */
    }

    public FileUploadDBBiz() {

    }

    @Override
    public void create(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
    }

    public void dropTable(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS " + tableName);
    }

    @Override
    public void upgrade(SQLiteDatabase db) {
        db.beginTransaction();
        db.execSQL(DROP_TEMP_TABLE);
        db.execSQL(RENAME_TO_TEMP_TABLE);
        db.execSQL(TABLE_CREATE);
        db.execSQL(COPY_TEMP_TO_NEW_TABLE);
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    /**
     * 保存文件上传保存到到本地数据库
     */
    public int saveMediaBean(MediaBean mBean) {
        where = InsertTime + "='" + mBean.insert_time + "' and " + FilePath + "='"
                + mBean.content + "'";
        values = new ContentValues();
        //插入时间
        values.put(InsertTime, mBean.insert_time);
        values.put(FileType, mBean.file_type);
        //服务器路径
        values.put(FileUrl, mBean.file_url);
        //文件名
        values.put(FileName, mBean.file_name);
        //本地路径
        values.put(FilePath, mBean.content);
        //上传状态
        values.put(FileState, mBean.file_state);
        values.put(FileSuffix, mBean.content_type);
        //图片拍摄时间
        values.put(PicShootTime, mBean.pic_shoot_time);
        //时长和大小
        String durationAndSize = mBean.file_dutime + "@" + mBean.file_size;
        values.put(Remark1, durationAndSize);
        return super.saveOrUpdate(tableName);

    }

    /**
     * 查询list
     */
    public List<MediaBean> queryBeanList(String insertTime) {
        where = InsertTime + " = '" + insertTime + "'";
        List<MediaBean> list = new ArrayList<>();
        Cursor cur;
        cur = db.query(tableName, where);
        while (cur.moveToNext()) {
            MediaBean bean = new MediaBean();
            bean.insert_time = cur.getString(1);//insertTime
            bean.file_type = cur.getString(cur.getColumnIndex(FileType));
            bean.file_url = cur.getString(cur.getColumnIndex(FileUrl));
            bean.file_name = cur.getString(cur.getColumnIndex(FileName));
            bean.file_state = cur.getString(cur.getColumnIndex(FileState));
            bean.content = cur.getString(cur.getColumnIndex(FilePath));
            bean.content_type = cur.getString(cur.getColumnIndex(FileSuffix));
            bean.pic_shoot_time = cur.getString(cur.getColumnIndex(PicShootTime));
            String durationAndSize = cur.getString(cur.getColumnIndex(Remark1));
            bean.file_dutime = durationAndSize.substring(0, durationAndSize.indexOf("@"));
            bean.file_size = durationAndSize.substring(durationAndSize.indexOf("@") + 1);
            LogUtil.d(TAG, "单个附件 logId " + insertTime + "fileType " + bean.file_type + " file content " +
                    bean.content);
            list.add(bean);
        }
        cur.close();
        LogUtil.d(TAG, "附件list 查询得到  logId " + insertTime + "list size " + list.size());
        return list;
    }

    private static final String TAG = "FileUploadDBBiz";

//    public MediaBean queryFirstBeanByTime(String insertTime) {
//        where = InsertTime + " = '" + insertTime + "'";
//        MediaBean mediaBean = new MediaBean();
//        Cursor cur = null;
//        try {
//            cur = db.query(tableName, where);
//            if (cur != null) {
//                if (cur.moveToFirst()) {
//                    mediaBean.insert_time = cur.getString(1);
//                    mediaBean.file_type = cur.getString(2);
//                    mediaBean.file_url = cur.getString(3);
//                    mediaBean.file_name = cur.getString(4);
//                    mediaBean.content = cur.getString(5);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            closeDbAndCursor(cur);
//        }
//        return mediaBean;
//    }


//    /**
//     * 查询保存的sort信息
//     */
//    public List<SortBean> queryUpSort(String where) {
//        where = "mid='" + where + "'";
//        List<SortBean> list = new ArrayList<SortBean>();
//
//        try {
//            Cursor cur = db.query(sortTable, where);
//            if (cur != null) {
//                for (int i = 0; i < cur.getCount(); i++) {
//                    if (cur.moveToPosition(i)) {
//                        SortBean bean = new SortBean();
//                        bean.obid = cur.getString(1);
//                        bean.name = cur.getString(2);
//                        bean.isLeaf = cur.getString(3);
//                        bean.pid = cur.getString(4);
//                        list.add(bean);
//                    }
//                }
//            }
//            cur.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return list;
//    }


    /**
     * 删除保存的sort信息
     */
    public int deleteAllSort() {
        return super.delete(tableName);
    }

    public int deleteRowByLogId(String logId) {
        selection = InsertTime + "= ?";
        selectionArgs = new String[]{logId};
        int result = super.delete(tableName);
        LogUtil.d(TAG, "deleteRowByLogId >>logId>>" + logId + " result" + result);
        return result;
    }
}
